<template>
  <div>
    <div class="warnningTip">
      <i class="el-icon-warning-outline" />
      {{ $t('message.dbjsysm') }}
    </div>
    <el-tabs v-model="manufacturer" @tab-click="handleQuery">
      <el-tab-pane
        v-for="model in manufacturerList"
        :key="model.id"
        :label="model.manufacturer"
        :name="model.id"
      />
    </el-tabs>
    <QueryForm
      v-model="filters"
      :query-form-config="deviceFormConfig"
      @handleQuery="handleQuery"
      @clear="clear"
    />
    <PageContent
      :list="list"
      :list-loading="listLoading"
      :total-count="totalCount"
      :page="pagination.page"
      v-bind="deviceContentConfig"
      @currentChange="currentChange"
      @SizeChange="SizeChange"
    >
      <template v-if="meta.indexOf('CoinsAdd') > -1" #header>
        <el-button
          v-if="meta.indexOf('CoinsAdd') > -1"
          v-preventReClick
          type="primary"
          @click="deviceAdd"
        >
          {{ $t('message.xinjian') }}
        </el-button>
      </template>
      <!-- 2.列中的插槽 -->
      <template #linkStatus="scope">
        <span>
          {{ scope.row.connectStatus == '1' ? $t('message.zaixian') : $t('message.lixian') }}
        </span>
      </template>
      <template #status="scope">
        <el-switch
          v-model="scope.row.status"
          active-value="1"
          inactive-value="0"
          :disabled="meta.indexOf('CoinsUpdateStatus') == -1"
          @change="statusChange(scope.row)"
        />
      </template>
      <template #handler="scope">
        <div class="flex-cc">
          <el-popover
            placement="bottom-start"
            :width="$i18n.locale === 'ZH'? 130 : 320"
            trigger="hover"
          >
            <div style="padding: 10px 0;">
              <div class="mb10 pointer" style="text-align: center" @click="downEwmPic(scope.row.ewmPic)">{{ $t('message.xcxewm') }}</div>
              <div class="pointer" style="text-align: center" @click="downEwmPic(scope.row.ewmH5Pic)">{{ $t('message.hewm') }}</div>
            </div>
            <el-button
              v-if="meta.indexOf('CoinsDown') > -1"
              slot="reference"
              type="text"
              class="mr10"
            >
              {{ $t('message.xzewm') }}
            </el-button>
          </el-popover>
          <el-button
            v-if="meta.indexOf('CoinsUpdate') > -1"
            type="text"
            @click="handleEditClick(scope.row)"
          >
            {{ $t('message.edit') }}
          </el-button>
          <el-button
            v-if="meta.indexOf('CoinsDel') > -1"
            type="text"
            class="secondColor"
            @click="handleDeleteClick(scope.row)"
          >{{ $t('message.del') }}</el-button>
        </div>
      </template>
    </PageContent>

    <el-dialog
      :title="ModalTitle"
      :visible.sync="isShowModal"
      :close-on-click-modal="closeModal"
      :close-on-press-escape="closeModal"
      width="600px"
    >
      <el-form
        ref="form"
        class="doumee-form"
        :model="deviceParam"
        :rules="deviceRules"
        label-width="auto"
        label-suffix="："
      >
        <el-form-item :label="$t('message.sbId')" prop="deviceId">
          <el-input
            v-model="deviceParam.deviceId"
            :placeholder="$t('message.qsr') + $t('message.sbId')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sbmc')" prop="name">
          <el-input
            v-model="deviceParam.name"
            :placeholder="$t('message.qsr') + $t('message.sbmc')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.sbzt')">
          <el-switch
            v-model="deviceParam.status"
            active-value="1"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowModal = false">{{ $t('message.qx') }}</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :loading="subLoading"
          @click="handleModelEnter"
        >{{ $t('message.qr') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QueryForm from '@/components/QueryForm'
import PageContent from './pagecContent'
import dayjs from 'dayjs'

import { deviceFormConfig, deviceContentConfig, deviceRules } from './config'
import {
  manufacturerList,
  coinsDevicesListPost,
  coinsDevicesAdd,
  coinsDevicesEdit,
  coinsDevicesUpdate,
  coinsDevicesDel
} from '@/api'
export default {
  components: {
    QueryForm,
    PageContent
  },
  props: {
    meta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      filters: {},
      deviceFormConfig,
      deviceContentConfig,
      list: [],
      listLoading: false,
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      },
      totalCount: 0,
      manufacturer: '',
      manufacturerList: [],
      closeModal: this.$store.getters.dialog,
      isShowModal: false,
      subLoading: false,
      ModalTitle: this.$t('message.add') + this.$t('message.dbj'),
      deviceParam: {},
      deviceRules
    }
  },
  created() {
    this.getManufacturer()
  },
  methods: {
    handleQuery() {
      this.pagination.page = 1
      this.getList()
    },
    async getList() {
      const { pagination, filters } = this
      filters.manufacturer = this.manufacturer
      this.listLoading = true
      try {
        const res = await coinsDevicesListPost({ pagination, param: filters })
        this.list = res.recordList
        this.totalCount = res.totalCount
      } catch (err) {
        console.log('error')
      } finally {
        this.listLoading = false
      }
    },
    deviceAdd() {
      this.deviceParam = {
        status: '0'
      }
      this.ModalTitle = this.$t('message.add') + this.$t('message.dbj')
      this.isShowModal = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    downEwmPic(pic) {
      const a = document.createElement('a') // 创建一个a标签元素
      a.style.display = 'none' // 设置元素不可见
      a.href = pic // 设置下载地址
      document.body.appendChild(a) // 加入
      a.click() // 触发点击,下载
      document.body.removeChild(a)
    },
    currentChange(val) {
      this.pagination.page = val
      this.getList()
    },
    SizeChange(val) {
      this.pagination.rows = val
      this.getList()
    },
    handleEditClick(item) {
      this.deviceParam = item
      this.ModalTitle = this.$t('message.edit') + this.$t('message.dbj')
      this.isShowModal = true
    },
    statusChange(item) {
      const { id, status } = item
      coinsDevicesUpdate({ param: { id, status }}).then(res => {
        this.handleQuery()
        if (res.errorCode !== '000000') return
        this.$message.success(this.$t('message.ztxgcg'))
      }, () => {
        this.handleQuery()
      })
    },
    handleDeleteClick(item) {
      const that = this
      this.$confirm(this.$t('message.scdbjtc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          coinsDevicesDel({ param: { id: item.id }}).then(res => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success(this.$t('message.delcg'))
              that.handleQuery()
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    handleModelEnter() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const param = this.deviceParam
          param.manufacturer = this.manufacturer
          let fn, message
          if (this.deviceParam.id) {
            fn = coinsDevicesEdit
            message = this.$t('message.editcg')
          } else {
            fn = coinsDevicesAdd
            message = this.$t('message.addcg')
          }
          this.subLoading = true
          fn({ param }).then(
            (res) => {
              this.subLoading = false
              if (res.errorCode !== '000000') return
              this.$message.success(message)
              this.isShowModal = false
              this.handleQuery()
            },
            () => {
              this.subLoading = false
            }
          )
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // this.isShowModal = false
    },
    getManufacturer() {
      manufacturerList({ param: { type: 7 }})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.manufacturerList = res.recordList.map(i => {
              i.id = String(i.id)
              return i
            })
            if (res.recordList.length > 0) {
              this.manufacturer = res.recordList[0].id
            }
            this.handleQuery()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    clear() {
      this.filters = {}
      this.handleQuery()
    }
  }
}
</script>

<style>
</style>
